/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/


#include "ge_local.h"
#include <algorithm>
#include <queue>
#include <stack>

/*-----------------------------------------------------------------------------
	Scene :
-----------------------------------------------------------------------------*/

//
//	EScene::WriteXML
//
EScene::EScene( EGeometryFactory *ge )
{
	this->ge	=	ge;
	root		=	ge->CreateSceneNode();
	root->SetName("root");
}


//
//	EScene::WriteXML
//
EScene::~EScene( void )
{
	Clear();
}


void EScene::BreakHierarchy( IPxSceneNode node )
{
	for (uint i=0; i<node->GetChildNum(); i++) {
		BreakHierarchy( node->GetChild(i) );
	}
	
	node->DetachAll();
}


//
//	EScene::Clear
//
void EScene::Clear( void )
{
	BreakHierarchy( root );
	root	=	ge->CreateSceneNode();
}


//
//	EScene::WriteXML
//
void EScene::WriteXML( rapidxml::xml_node<> *xnode ) const
{
	WriteXMLRecursive( xnode, root );
}


void EScene::WriteXMLRecursive(rapidxml::xml_node<> *xparent_node, const IPxSceneNode node) const
{
	xml_document<>	*xdoc = xparent_node->document();

	xml_node<>	*xml_scene_node	=	xdoc->allocate_node(node_element, "scene_node");
	xparent_node->append_node(xml_scene_node);
	
	//	write node :
	node->WriteXML(xml_scene_node);
	
	//	write subnodes :
	for (uint i=0; i<node->GetChildNum(); i++) {
		WriteXMLRecursive(xml_scene_node, node->GetChild(i));
	}	
}


//
//	EScene::ReadXML
//
void EScene::ReadXML( rapidxml::xml_node<> *xnode )
{
	Clear();

	xml_node<>	*xml_root_node	=	xnode->first_node("scene_node");
	
	if (!xml_root_node) {
		RUNTIME_ERROR("root <scene_node> not found");
	}
	
	root->ReadXML( xml_root_node );
	
	ReadXMLRecursive( xml_root_node, root );
}


void EScene::ReadXMLRecursive(xml_node<> *xparent_node, IPxSceneNode parent_node)
{
	xml_document<>	*xdoc		=	xparent_node->document();
	
	xml_node<>	*xml_scene_node	=	xparent_node->first_node("scene_node");
	
	for ( ; xml_scene_node ; xml_scene_node = xml_scene_node->next_sibling("scene_node") ) {
		
		IPxSceneNode	scene_node = ge->CreateSceneNode() ; 
		
		scene_node->ReadXML( xml_scene_node );
		
		parent_node->AttachChild( scene_node );
		
		ReadXMLRecursive( xml_scene_node, scene_node );
	}
}


//
//	EScene::GetIterator
//
IPxSceneIt EScene::GetIterator( ESceneIterType_s iter_type )
{
	return new ESceneIt( root, iter_type );
}


//
//	EScene::GetNode
//	get nodes by its hierarchy path: "|pCube|pCylinder"
//
IPxSceneNode EScene::GetNodeByPath( const char *_path )
{
	EString	path	=	_path;
	
	std::vector<EString>	names;

		
	int begin = path.Find('|', 0);
	int end = begin;
	if (begin==EString::NPOS) {
		RUNTIME_ERROR(va("wrong scene path : '%s'", _path));
	}

	while (begin!=EString::NPOS) {
		EString name;
		
		end		=	path.Find('|', begin+1);
		
		name	=	path.Substr(begin+1, end);
		
		begin	=	end;
		names.push_back(name);
	}
	
	IPxSceneNode	node = root;
	
	for (uint i=0; i<names.size(); i++) {
		node	=	node->GetChild( names[i] );
		if (!node) {
			return NULL;
		}
	}
	return node;
}

/*-----------------------------------------------------------------------------
	Scene node :
-----------------------------------------------------------------------------*/

ESceneNode::ESceneNode( EGeometryFactory *ge )
{
	this->ge	=	ge;
	
	position	=	EPoint(0,0,0);
	orient		=	EQuaternion();
	
	SetAffector(NULL);
}


ESceneNode::~ESceneNode( void )
{

}


void ESceneNode::GetLocalPose( EPoint &pos, EQuaternion &orient ) const
{
	pos		=	this->position;
	orient	=	this->orient;
}


void ESceneNode::SetLocalPose( const EPoint &pos, const EQuaternion &orient )
{
	this->position	=	pos;
	this->orient	=	orient;
}


//
//	ESceneNode::GetGlobalPose
//
void ESceneNode::GetGlobalPose( EPoint &pos, EQuaternion &orient ) const
{
	EMatrix		transform = EMatrix();
	IPxSceneNode	node = const_cast<ESceneNode*>(this);
	
	while ( node ) {

		EQuaternion		q;
		EPoint			t;
		node->GetLocalPose( t, q );

		EMatrix	T	=	EMatrix::Translate( EVector(t) );
		EMatrix	R	=	q.ToMatrix();

		transform		=	transform * R * T;

		node = node->GetParent();
	}

	pos.x	=	transform(3,0);
	pos.y	=	transform(3,1);
	pos.z	=	transform(3,2);
	pos.w	=	transform(3,3);

	orient	=	EQuaternion::FromMatrix( transform );
}


//
//	ESceneNode::GetPath
//
EString ESceneNode::GetPath( void ) const
{
	EString	path	=	"";
	IPxSceneNode	node = const_cast<ESceneNode*>(this);
	
	while ( node ) {
	
		//	dont include root node 'world' :
		if (!node->GetParent()) {
			break;
		}

		path	=	va("|%s%s", node->GetName().CStr(), path.CStr());
		node	=	node->GetParent();
	}
	
	return path;
}


//
//	ESceneNode::AttachChild
//
void ESceneNode::AttachChild( IPxSceneNode entity )
{
	ASSERT( entity!=NULL );
	
	if (entity.to<ESceneNode>()->parent==this) {
		return;
	}

	//	if entity is already attached, detach it :
	if (entity.to<ESceneNode>()->parent) {
		entity.to<ESceneNode>()->parent->DetachChild( entity );
	}

	//	search for the already added entity :
	children.push_back( entity );
	entity.to<ESceneNode>()->parent = this;
}


//
//	ESceneNode::DetachChild
//
void ESceneNode::DetachChild( IPxSceneNode entity )
{
	ASSERT( entity!=NULL );

	std::vector<IPxSceneNode>::iterator	vi;
	vi = find(children.begin(), children.end(), entity);

	if (vi==children.end()) {
		return;
	}	
	
	children.erase( vi );
	entity.to<ESceneNode>()->parent = NULL;
}


//
//	ESceneNode::DetachChild
//
void ESceneNode::DetachChild( uint index )
{
	ASSERT( index < GetChildNum() );

	std::vector<IPxSceneNode>::iterator	vi;
	vi	=	children.begin() + index;

	children.erase( vi );
	(*vi).to<ESceneNode>()->parent = NULL;
}


//
//	ESceneNode::DetachAll
//
void ESceneNode::DetachAll( void )
{
	for (uint i=0; i<children.size(); i++) {
		children[i].to<ESceneNode>()->parent	=	NULL;
	}
	children.clear();
}


//
//	ESceneNode::GetChildNum
//
uint ESceneNode::GetChildNum( void ) const
{
	return children.size();
}


//
//	ESceneNode::GetChild
//
IPxSceneNode ESceneNode::GetChild( uint index )
{
	ASSERT( index < GetChildNum() );
	return children[ index ];
}


//
//	ESceneNode::GetChild
//
const IPxSceneNode ESceneNode::GetChild( uint index ) const
{
	ASSERT( index < GetChildNum() );
	return children[ index ];
}


//
//	ESceneNode::GetChild
//
IPxSceneNode ESceneNode::GetChild( EString name )
{
	for (uint i=0; i<children.size(); i++) {
		if (children[i]->GetName()==name) {
			return children[i];
		}
	}
	return NULL;
}


//
//	ESceneNode::GetChild
//
const IPxSceneNode ESceneNode::GetChild( EString name ) const
{
	for (uint i=0; i<children.size(); i++) {
		if (children[i]->GetName()==name) {
			return children[i];
		}
	}
	return NULL;
}


//
//	ESceneNode::SetParent
//
void ESceneNode::SetParent( IPxSceneNode parent )
{
	if (this->parent==parent) {
		return;
	}

	if (parent) {
		parent->AttachChild( this );
	} else {
		this->parent->DetachChild( this );
	}
}


//
//	ESceneNode::GetScenePath
//
EString ESceneNode::GetScenePath( void ) const
{
	std::string path = "";
	IPxSceneNode	node	=	const_cast<ESceneNode*>(this);
	
	path	=	node->GetName().CStr();
	node	=	node->GetParent();
	
	while (node && node->GetParent()) {
		path	=	va("%s|%s", node->GetName().CStr(), path.c_str());
		node	=	node->GetParent();
	}
	
	path = va("|%s", path.c_str());
	
	return path.c_str();
}


//
//	ESceneNode::GetAffector
//
const char * ESceneNode::GetAffector( const char *key, const char *def_value ) const
{
	if (!key) {
		if (affector_str.empty()) {
			return NULL;
		}
		return affector_str.c_str();
	}

	int index = 0;
	if (affector.CheckParam(key, &index)) {
		const char *param = affector.Argv(index+1);
		if (param[0]!='-') {
			return param;
		} else {
			return "";
		}
	} else {
		return def_value;
	}
}


//
//	ESceneNode::SetAffector
//
void ESceneNode::SetAffector( const char *affector_string )
{
	if (affector_string) {
		affector_str	=	affector_string;
	} else {
		affector_str	=	"";
	}
	affector.Tokenize( affector_str.c_str() );
}


void ESceneNode::AddAffector( const char *affector_string )
{
	affector_str += " ";
	affector_str += affector_string;

	affector.Tokenize( affector_str.c_str() );
}


/*-----------------------------------------------------------------------------
	XML stuff :
-----------------------------------------------------------------------------*/

//
//	ESceneNode::WriteXML
//
void ESceneNode::WriteXML( rapidxml::xml_node<> *xnode ) const
{
	xml_document<>	*xdoc = xnode->document();
	xml_node<>	*xml_mesh	=	xdoc->allocate_node(node_element, "mesh");

	if (mesh) {
		xnode->append_node( xml_mesh );
		mesh->WriteXML(xml_mesh);
	}
	
	xml_add_attr<char>( xnode, "name",		name.CStr() );
	xml_add_attr<char>( xnode, "class",		classname.CStr() );
	xml_add_attr<char>( xnode, "affector",	affector_str.c_str() );
	xml_add_attr<char>( xnode, "position",	va("%g %g %g %g", position.x, position.y, position.z, position.w) );
	xml_add_attr<char>( xnode, "orient",	va("%g %g %g %g", orient.x, orient.y, orient.z, orient.w) );
}


//
//	ESceneNode::ReadXML
//
void ESceneNode::ReadXML( rapidxml::xml_node<> *xnode )
{
	xml_document<>	*xdoc	=	xnode->document();
	xml_node<>	*xml_mesh	=	xnode->first_node("mesh");

	if (xml_mesh) {
		mesh = ge->CreateTriMesh(GE_MESH_POSITION);
		mesh->ReadXML(xml_mesh);
	} else {
		mesh = NULL;
	}
	
	name			=	xml_get_attr<char>(xnode, "name",		"");
	classname		=	xml_get_attr<char>(xnode, "class",		"");
	position		=	EPoint::FromString( xml_get_attr<char>(xnode, "position",	"0 0 0 1") );
	orient			=	EQuaternion::FromString( xml_get_attr<char>(xnode, "orient","0 0 0 1") );

	SetAffector	( xml_get_attr<char>(xnode, "affector",	"") );
}
/*-----------------------------------------------------------------------------
	Scene iterator :
-----------------------------------------------------------------------------*/

ESceneIt::ESceneIt( IPxSceneNode root, ESceneIterType_s type )
{
	if (type==SCENE_ITERATOR_BFS) {
		FillListBFS(root);
	} else {
		FillListDFS(root);
	}
	Reset();
}


ESceneIt::~ESceneIt( void )
{

}


void ESceneIt::FillListBFS( IPxSceneNode root )
{
	queue<IPxSceneNode>	Q;
	Q.push(root);
	
	while (!Q.empty()) {
		IPxSceneNode n = Q.front();
		Q.pop();
	
		sequence.push_back( n );
		
		for (uint i=0; i<n->GetChildNum(); i++) {
			Q.push( n->GetChild(i) );
		}
	}
}


void ESceneIt::FillListDFS( IPxSceneNode root )
{
	stack<IPxSceneNode>	Q;
	Q.push(root);
	
	while (!Q.empty()) {
		IPxSceneNode n = Q.top();
		Q.pop();
	
		sequence.push_back( n );
		
		for (uint i=0; i<n->GetChildNum(); i++) {
			Q.push( n->GetChild(i) );
		}
	}
}


void ESceneIt::Reset( void )
{
	done	=	false;
	iter	=	sequence.begin();
}


bool ESceneIt::Done( void )
{
	return done;
}


void ESceneIt::Next( void )
{
	if (!done) {
		iter++;
	}
	if (iter==sequence.end()) {
		done = true;
	}
}


IPxSceneNode ESceneIt::Current( void )
{
	return *iter;
}